{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "initial_id",
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    ""
   ]
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# 1、字符串输出解析器 StrOutputParser",
   "id": "6263377f0858da0f"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T20:15:58.839241Z",
     "start_time": "2025-09-28T20:15:56.053082Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "# 1、获取大模型\n",
    "from langchain_core.messages import HumanMessage, SystemMessage\n",
    "from langchain_core.output_parsers import StrOutputParser, XMLOutputParser\n",
    "\n",
    "import os\n",
    "import dotenv\n",
    "from langchain_core.utils import pre_init\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv(\"OPENAI_API_KEY1\")\n",
    "os.environ['OPENAI_BASE_URL'] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "# 2、调用大模型\n",
    "response = chat_model.invoke(\"什么是大语言模型？\")\n",
    "# print(type(response))   #AIMessage\n",
    "\n",
    "#3、如何获取一个字符串的输出结果呢？\n",
    "# 方式1：自己调用输出结果的content\n",
    "# print(response.content)\n",
    "\n",
    "# 方式2：使用StrOutputParser\n",
    "parser = StrOutputParser()\n",
    "str_response = parser.invoke(response)\n",
    "print(type(str_response))  #<class 'str'>\n",
    "print(str_response)\n"
   ],
   "id": "6148600b6d3e6e26",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'str'>\n",
      "大语言模型（Large Language Model，简称LLM）是一种基于深度学习的自然语言处理模型，能够理解、生成和处理人类语言。这些模型通常通过海量文本数据进行训练，以捕捉语言的结构、语法、语义等特征。\n",
      "\n",
      "大语言模型的主要特点包括：\n",
      "\n",
      "1. **规模**：通常包含数亿到数千亿个参数，这使得模型能够更好地理解复杂的语言模式。\n",
      "\n",
      "2. **预训练和微调**：大语言模型通常使用无监督学习进行预训练，然后通过有监督学习进行微调，以特定任务（如文本分类、对话生成等）来优化模型性能。\n",
      "\n",
      "3. **上下文理解**：能够基于上下文生成连贯的文本，回答问题，进行对话等。\n",
      "\n",
      "4. **多任务学习**：可以在多种自然语言处理任务中表现良好，如翻译、摘要、情感分析等。\n",
      "\n",
      "5. **应用广泛**：被广泛应用于聊天机器人、自动写作、内容生成、搜索引擎、语言翻译等领域。\n",
      "\n",
      "一些著名的大语言模型包括OpenAI的GPT-3和GPT-4、Google的BERT和T5、以及Meta的LLaMA等。这些模型的出现极大地推动了自然语言处理领域的进步。\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 2、JsonOutputParser : Json输出解析器\n",
    "\n",
    "方式1："
   ],
   "id": "ad74e61765517684"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T20:19:43.935251Z",
     "start_time": "2025-09-28T20:19:43.210900Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain_core.output_parsers import JsonOutputParser\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "chat_prompt_template = ChatPromptTemplate.from_messages([\n",
    "    (\"system\", \"你是一个靠谱的{role}\"),\n",
    "    (\"human\", \"{question}\")\n",
    "])\n",
    "\n",
    "# 正确的：\n",
    "prompt = chat_prompt_template.invoke(\n",
    "    input={\"role\": \"人工智能专家\", \"question\": \"人工智能用英文怎么说？问题用q表示，答案用a表示，返回一个JSON格式的数据\"})\n",
    "\n",
    "# 错误的：\n",
    "# prompt = chat_prompt_template.invoke(input={\"role\":\"人工智能专家\",\"question\":\"人工智能用英文怎么说？\"})\n",
    "\n",
    "response = chat_model.invoke(prompt)\n",
    "print(response.content)\n",
    "\n",
    "# 获取一个JsonOutputParser的实例\n",
    "parser = JsonOutputParser()\n",
    "json_result = parser.invoke(response)\n",
    "print(json_result)"
   ],
   "id": "c417b377c3e25eaf",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "```json\n",
      "{\n",
      "  \"q\": \"人工智能用英文怎么说？\",\n",
      "  \"a\": \"Artificial Intelligence\"\n",
      "}\n",
      "```\n",
      "{'q': '人工智能用英文怎么说？', 'a': 'Artificial Intelligence'}\n"
     ]
    }
   ],
   "execution_count": 7
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "方式2：\n",
    "\n",
    "举例1："
   ],
   "id": "141259590b693db5"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T20:20:29.400458Z",
     "start_time": "2025-09-28T20:20:29.394237Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "parser = JsonOutputParser()\n",
    "\n",
    "print(parser.get_format_instructions())"
   ],
   "id": "4fa3120ee3fe846a",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Return a JSON object.\n"
     ]
    }
   ],
   "execution_count": 8
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：",
   "id": "2c028c2187c9a4ac"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T20:23:07.962646Z",
     "start_time": "2025-09-28T20:23:06.797285Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "# 引入依赖包\n",
    "from langchain_core.output_parsers import JsonOutputParser\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "\n",
    "# 初始化语言模型\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "joke_query = \"告诉我一个笑话。\"\n",
    "\n",
    "# 定义Json解析器\n",
    "parser = JsonOutputParser()\n",
    "\n",
    "#以PromptTemplate为例\n",
    "prompt_template = PromptTemplate.from_template(\n",
    "    template=\"回答用户的查询\\n 满足的格式为{format_instructions}\\n 问题为{question}\\n\",\n",
    "    partial_variables={\"format_instructions\": parser.get_format_instructions()},\n",
    ")\n",
    "\n",
    "prompt = prompt_template.invoke(input={\"question\": joke_query})\n",
    "response = chat_model.invoke(prompt)\n",
    "print(response)\n",
    "\n",
    "json_result = parser.invoke(response)\n",
    "print(json_result)"
   ],
   "id": "ba93fb04cc3aefd2",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "content='{\\n  \"joke\": \"为什么鸟儿不使用社交媒体？因为它们已经有了推特！\"\\n}' additional_kwargs={'refusal': None} response_metadata={'token_usage': {'completion_tokens': 28, 'prompt_tokens': 32, 'total_tokens': 60, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_efad92c60b', 'id': 'chatcmpl-CKsDD9N1k8D1FH7Rsvsn1JHfeATJP', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None} id='run--955af686-e110-4323-9349-66901b144c9c-0' usage_metadata={'input_tokens': 32, 'output_tokens': 28, 'total_tokens': 60, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}}\n",
      "{'joke': '为什么鸟儿不使用社交媒体？因为它们已经有了推特！'}\n"
     ]
    }
   ],
   "execution_count": 9
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "知识的拓展： |",
   "id": "e58f3893114e1fcf"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T20:28:01.010687Z",
     "start_time": "2025-09-28T20:27:59.833933Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain_core.output_parsers import JsonOutputParser\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "chat_prompt_template = ChatPromptTemplate.from_messages([\n",
    "    (\"system\", \"你是一个靠谱的{role}\"),\n",
    "    (\"human\", \"{question}\")\n",
    "])\n",
    "\n",
    "# 获取一个JsonOutputParser的实例\n",
    "parser = JsonOutputParser()\n",
    "\n",
    "# 写法1：\n",
    "# prompt = chat_prompt_template.invoke(input={\"role\":\"人工智能专家\",\"question\":\"人工智能用英文怎么说？问题用q表示，答案用a表示，返回一个JSON格式的数据\"})\n",
    "#\n",
    "# response = chat_model.invoke(prompt)\n",
    "#\n",
    "# json_result = parser.invoke(response)\n",
    "# print(json_result)\n",
    "\n",
    "# 写法2：\n",
    "chain = chat_prompt_template | chat_model | parser\n",
    "json_result1 = chain.invoke(\n",
    "    input={\"role\":\"人工智能专家\",\"question\":\"人工智能用英文怎么说？问题用q表示，答案用a表示，返回一个JSON格式的数据\"}\n",
    ")\n",
    "print(json_result1)"
   ],
   "id": "ae9da8d72b4a5c3a",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'q': '人工智能用英文怎么说？', 'a': 'Artificial Intelligence'}\n"
     ]
    }
   ],
   "execution_count": 10
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "针对于举例2",
   "id": "d373f1bebd29bfd5"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T20:28:44.635962Z",
     "start_time": "2025-09-28T20:28:43.038887Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "# 引入依赖包\n",
    "from langchain_core.output_parsers import JsonOutputParser\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "\n",
    "# 初始化语言模型\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "joke_query = \"告诉我一个笑话。\"\n",
    "\n",
    "# 定义Json解析器\n",
    "parser = JsonOutputParser()\n",
    "\n",
    "#以PromptTemplate为例\n",
    "prompt_template = PromptTemplate.from_template(\n",
    "    template=\"回答用户的查询\\n 满足的格式为{format_instructions}\\n 问题为{question}\\n\",\n",
    "    partial_variables={\"format_instructions\": parser.get_format_instructions()},\n",
    ")\n",
    "# 写法1：\n",
    "# prompt = prompt_template.invoke(input={\"question\":joke_query})\n",
    "# response = chat_model.invoke(prompt)\n",
    "# json_result = parser.invoke(response)\n",
    "\n",
    "chain = prompt_template | chat_model | parser\n",
    "json_result = chain.invoke(input={\"question\": joke_query})\n",
    "print(json_result)"
   ],
   "id": "ca7e1321250176e9",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'joke': \"为什么图书馆那么安静？因为书都在 '静' 沉思！\"}\n"
     ]
    }
   ],
   "execution_count": 11
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 3、XMLOutputParser XML输出解析器的使用\n",
    "\n",
    "举例1：自己在提示词模板中写明使用XML格式"
   ],
   "id": "83706571e3eb4057"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T20:29:36.416626Z",
     "start_time": "2025-09-28T20:29:32.684262Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "actor_query = \"周星驰的简短电影记录\"\n",
    "response = chat_model.invoke(f\"请生成{actor_query}，将影片附在<movie></movie>标签中\")\n",
    "\n",
    "print(type(response))\n",
    "print(response.content)"
   ],
   "id": "65da6b40f55183eb",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'langchain_core.messages.ai.AIMessage'>\n",
      "周星驰是中国香港的一位著名电影演员、导演和编剧，以其独特的喜剧风格和深刻的社会观察而闻名。以下是周星驰的一些经典电影记录：\n",
      "\n",
      "<movie>\n",
      "1. **《大话西游之月光宝盒》（1995）**\n",
      "   - 简介：周星驰扮演的孙悟空历经风雨，寻找真爱的故事，本片以其深刻的情感和幽默的桥段而广受喜爱。\n",
      "\n",
      "2. **《喜剧之王》（1999）**\n",
      "   - 简介：讲述了一位志向成为演员的年轻人的奋斗与爱情，展现了周星驰对喜剧的理解和对梦想的执着。\n",
      "\n",
      "3. **《少林足球》（2001）**\n",
      "   - 简介：融合了足球和武术元素，讲述了一群少林寺僧人如何用足球改变生活的搞笑故事，深受观众好评。\n",
      "\n",
      "4. **《功夫》（2004）**\n",
      "   - 简介：在一场赌注和功夫的较量中，展现了周星驰的导演才华与功夫喜剧的魅力，演绎了一个关于梦想与正义的故事。\n",
      "\n",
      "5. **《长江七号》（2008）**\n",
      "   - 简介：这是一部结合了科幻与亲情元素的影片，讲述了父子之间的温情故事，展现了周星驰对亲情的独特理解。\n",
      "</movie>\n",
      "\n",
      "周星驰的影片通常结合了幽默、爱情和人生哲理，使得他的电影成为了华语电影中不可磨灭的经典。\n"
     ]
    }
   ],
   "execution_count": 12
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：",
   "id": "57c9b4dd5ce76dd5"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T20:30:31.053265Z",
     "start_time": "2025-09-28T20:30:31.046967Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain_core.output_parsers.xml import XMLOutputParser\n",
    "\n",
    "parser = XMLOutputParser()\n",
    "print(parser.get_format_instructions())"
   ],
   "id": "6b16f2cff1a6bc4c",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The output should be formatted as a XML file.\n",
      "1. Output should conform to the tags below.\n",
      "2. If tags are not given, make them on your own.\n",
      "3. Remember to always open and close all the tags.\n",
      "\n",
      "As an example, for the tags [\"foo\", \"bar\", \"baz\"]:\n",
      "1. String \"<foo>\n",
      "   <bar>\n",
      "      <baz></baz>\n",
      "   </bar>\n",
      "</foo>\" is a well-formatted instance of the schema.\n",
      "2. String \"<foo>\n",
      "   <bar>\n",
      "   </foo>\" is a badly-formatted instance.\n",
      "3. String \"<foo>\n",
      "   <tag>\n",
      "   </tag>\n",
      "</foo>\" is a badly-formatted instance.\n",
      "\n",
      "Here are the output tags:\n",
      "```\n",
      "None\n",
      "```\n"
     ]
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "使用parser.get_format_instructions()结构实现：",
   "id": "45f1c3f8170f313b"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T20:31:53.034941Z",
     "start_time": "2025-09-28T20:31:50.359505Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "# 1.导入相关包\n",
    "from langchain_core.output_parsers import XMLOutputParser\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "# 2. 初始化语言模型\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "# 3.测试模型的xml解析效果\n",
    "actor_query = \"生成汤姆·汉克斯的简短电影记录,使用中文回复\"\n",
    "\n",
    "# 4.定义XMLOutputParser对象\n",
    "parser = XMLOutputParser()\n",
    "\n",
    "# 5. 生成提示词模板\n",
    "prompt_template1 = PromptTemplate.from_template(\n",
    "    template=\"用户的问题：{query}\\n使用的格式：{format_instructions}\"\n",
    ")\n",
    "\n",
    "prompt_template2 = prompt_template1.partial(format_instructions=parser.get_format_instructions())\n",
    "\n",
    "\n",
    "response = chat_model.invoke(prompt_template2.invoke(input={\"query\": actor_query}))\n",
    "print(response.content)"
   ],
   "id": "ec27ddc1704350fa",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "```xml\n",
      "<电影记录>\n",
      "    <演员>\n",
      "        <姓名>汤姆·汉克斯</姓名>\n",
      "        <出生日期>1956-07-09</出生日期>\n",
      "        <国籍>美国</国籍>\n",
      "        <职业>演员、制片人、导演</职业>\n",
      "    </演员>\n",
      "    <代表作品>\n",
      "        <电影>\n",
      "            <标题>阿甘正传</标题>\n",
      "            <年份>1994</年份>\n",
      "            <角色>阿甘</角色>\n",
      "        </电影>\n",
      "        <电影>\n",
      "            <标题>拯救大兵瑞恩</标题>\n",
      "            <年份>1998</年份>\n",
      "            <角色>米勒上尉</角色>\n",
      "        </电影>\n",
      "        <电影>\n",
      "            <标题>费城故事</标题>\n",
      "            <年份>1993</年份>\n",
      "            <角色>安德鲁·贝肯</角色>\n",
      "        </电影>\n",
      "        <电影>\n",
      "            <标题>人生如戏</标题>\n",
      "            <年份>1998</年份>\n",
      "            <角色>查克·诺兰</角色>\n",
      "        </电影>\n",
      "        <电影>\n",
      "            <标题>芝加哥七君子审判</标题>\n",
      "            <年份>2020</年份>\n",
      "            <角色>律师</角色>\n",
      "        </电影>\n",
      "    </代表作品>\n",
      "</电影记录>\n",
      "```\n"
     ]
    }
   ],
   "execution_count": 14
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T20:32:29.523214Z",
     "start_time": "2025-09-28T20:32:29.516058Z"
    }
   },
   "cell_type": "code",
   "source": [
    "xml_result = parser.invoke(response)\n",
    "print(xml_result)"
   ],
   "id": "6dedf55f21373d98",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'电影记录': [{'演员': [{'姓名': '汤姆·汉克斯'}, {'出生日期': '1956-07-09'}, {'国籍': '美国'}, {'职业': '演员、制片人、导演'}]}, {'代表作品': [{'电影': [{'标题': '阿甘正传'}, {'年份': '1994'}, {'角色': '阿甘'}]}, {'电影': [{'标题': '拯救大兵瑞恩'}, {'年份': '1998'}, {'角色': '米勒上尉'}]}, {'电影': [{'标题': '费城故事'}, {'年份': '1993'}, {'角色': '安德鲁·贝肯'}]}, {'电影': [{'标题': '人生如戏'}, {'年份': '1998'}, {'角色': '查克·诺兰'}]}, {'电影': [{'标题': '芝加哥七君子审判'}, {'年份': '2020'}, {'角色': '律师'}]}]}]}\n"
     ]
    }
   ],
   "execution_count": 15
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 4、列表解析器 CommaSeparatedListOutputParser\n",
    "\n",
    "举例1："
   ],
   "id": "abf59736f6449dd4"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T20:33:28.626765Z",
     "start_time": "2025-09-28T20:33:28.616633Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain_core.output_parsers import CommaSeparatedListOutputParser\n",
    "\n",
    "output_parser = CommaSeparatedListOutputParser()\n",
    "\n",
    "# 返回一些指令或模板，这些指令告诉系统如何解析或格式化输出数据\n",
    "format_instructions = output_parser.get_format_instructions()\n",
    "print(format_instructions)\n",
    "\n",
    "messages = \"大象,猩猩,狮子\"\n",
    "result = output_parser.parse(messages)\n",
    "print(result)\n",
    "print(type(result))"
   ],
   "id": "e14fb355c9f98406",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Your response should be a list of comma separated values, eg: `foo, bar, baz` or `foo,bar,baz`\n",
      "['大象', '猩猩', '狮子']\n",
      "<class 'list'>\n"
     ]
    }
   ],
   "execution_count": 16
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：",
   "id": "90493bab6f51b82d"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T20:34:50.621562Z",
     "start_time": "2025-09-28T20:34:47.775527Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain.output_parsers import CommaSeparatedListOutputParser\n",
    "\n",
    "# 初始化语言模型\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "# 创建解析器\n",
    "output_parser = CommaSeparatedListOutputParser()\n",
    "\n",
    "# 创建LangChain提示模板\n",
    "chat_prompt = PromptTemplate.from_template(\n",
    "    \"生成5个关于{text}的列表.\\n\\n{format_instructions}\",\n",
    "    partial_variables={\n",
    "    \"format_instructions\": output_parser.get_format_instructions()\n",
    "    })\n",
    "\n",
    "# 提示模板与输出解析器传递输出\n",
    "# chat_prompt = chat_prompt.partial(format_instructions=output_parser.get_format_instructions())\n",
    "\n",
    "# 将提示和模型合并以进行调用\n",
    "chain = chat_prompt | chat_model | output_parser\n",
    "res = chain.invoke({\"text\": \"电影\"})\n",
    "print(res)\n",
    "print(type(res))"
   ],
   "id": "591b4c2e48cbdbce",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['1. 科幻电影：银翼杀手2049', '星际穿越', '黑客帝国', '异形', '终结者2  ', '2. 灾难电影：泰坦尼克号', '2021大海啸', '后天', '惊涛骇浪', '迷失Z城  ', '3. 动画电影：玩具总动员', '冰雪奇缘', '千与千寻', '寻梦环游记', '动物方城市  ', '4. 动作电影：复仇者联盟', '疯狂的麦克斯', '刀锋战士', '速度与激情', '夺命追踪  ', '5. 爱情电影：恋恋笔记本', '这个杀手不太冷', '乱世佳人', '北京遇上西雅图', '甜蜜蜜']\n",
      "<class 'list'>\n"
     ]
    }
   ],
   "execution_count": 17
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 5、日期解析器 DatetimeOutputParser\n",
    "\n",
    "举例1："
   ],
   "id": "da914201409d1286"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T20:35:35.105159Z",
     "start_time": "2025-09-28T20:35:35.099071Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain.output_parsers import DatetimeOutputParser\n",
    "\n",
    "output_parser = DatetimeOutputParser()\n",
    "\n",
    "format_instructions = output_parser.get_format_instructions()\n",
    "print(format_instructions)"
   ],
   "id": "f4bc733718bd48dd",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Write a datetime string that matches the following pattern: '%Y-%m-%dT%H:%M:%S.%fZ'.\n",
      "\n",
      "Examples: 2023-07-04T14:30:00.000000Z, 1999-12-31T23:59:59.999999Z, 2025-01-01T00:00:00.000000Z\n",
      "\n",
      "Return ONLY this string, no other words!\n"
     ]
    }
   ],
   "execution_count": 18
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：",
   "id": "28557113f15c708e"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T20:43:29.791557Z",
     "start_time": "2025-09-28T20:43:28.586901Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain.prompts.chat import HumanMessagePromptTemplate\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "from langchain.output_parsers import DatetimeOutputParser\n",
    "\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "\n",
    "chat_prompt = ChatPromptTemplate.from_messages([\n",
    "    (\"system\",\"{format_instructions}\"),\n",
    "    (\"human\", \"{request}\")\n",
    "])\n",
    "\n",
    "output_parser = DatetimeOutputParser()\n",
    "\n",
    "# 方式1：\n",
    "# model_request = chat_prompt.format_messages(\n",
    "#     request=\"中华人民共和国是什么时候成立的\",\n",
    "#     format_instructions=output_parser.get_format_instructions()\n",
    "# )\n",
    "\n",
    "# model_request = chat_prompt.invoke({\n",
    "#     \"request\":\"中华人民共和国是什么时候成立的\",\n",
    "#     \"format_instructions\":output_parser.get_format_instructions()\n",
    "# })\n",
    "#\n",
    "# response = chat_model.invoke(model_request)\n",
    "# result = output_parser.invoke(response)\n",
    "# print(result)\n",
    "# print(type(result))\n",
    "\n",
    "chain = chat_prompt | chat_model | output_parser\n",
    "result = chain.invoke(\n",
    "    {\n",
    "    \"request\":\"中华人民共和国是什么时候成立的\",\n",
    "    \"format_instructions\":output_parser.get_format_instructions()\n",
    "}\n",
    ")\n",
    "print(result)\n",
    "print(type(result))"
   ],
   "id": "5329901eac3cb155",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1949-10-01 00:00:00\n",
      "<class 'datetime.datetime'>\n"
     ]
    }
   ],
   "execution_count": 22
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
